package com.zyc.app.woa.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import com.zyc.app.woa.R;
import com.zyc.app.woa.data.CachedArticle;
import com.zyc.app.woa.db.ArticlesTable;
import com.zyc.app.woa.db.DBManager;
import com.zyc.app.woa.utils.Caches;
import com.zyc.app.woa.utils.Caches.CacheKey;
import com.zyc.app.woa.utils.StatisticUtil;
import com.zyc.app.woa.utils.Trace;

/**
 * Created by zyc on 12/27/14.
 */
public class ArticleActivity extends BaseActivity {
    private WebView mWebView;
    private CachedArticle mArticle;
    private Menu mMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_browser);
        mWebView = (WebView) findViewById(R.id.web_content);
        mArticle = (CachedArticle) Caches.get(CacheKey.READING_ARTICLE);
        Trace.log("article path: " + mArticle.cacheFile);
        loadContent();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.article_menu, menu);
        mMenu = menu;
        setFavoriteIconStatus(mArticle.isFavorite());
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_favorite:
                boolean favorite = mArticle.isFavorite();
                if (favorite) {
                    favorite = false;
                    mArticle.favorite = ArticlesTable.COLUMN_VALUE_NONE;
                } else {
                    favorite = true;
                    mArticle.favorite = ArticlesTable.COLUMN_VALUE_FAVORITE;
                    StatisticUtil.favoriteArticle(mArticle);
                }
                setFavoriteIconStatus(favorite);
                DBManager.updateArticleFavoriteStatus(mArticle, favorite);
                break;
            case R.id.action_origin:
                StatisticUtil.readOriginArticle(mArticle);
                startActivity(new Intent(getApplicationContext(), OriginActivity.class));
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private void loadContent() {
        mWebView.loadUrl("file://" + mArticle.cacheFile);
        getActionBar().setTitle(mArticle.title);
        DBManager.updateArticleReadStatus(mArticle, true);
        Trace.log("loadContent: " + mArticle.title + " read: " + mArticle.read);
    }

    private void setFavoriteIconStatus(boolean favorite) {
        if (null != mMenu) {
            MenuItem menuItem = mMenu.findItem(R.id.action_favorite);
            if (null != menuItem) {
                menuItem.setIcon(favorite ? R.drawable.ic_star : R.drawable.ic_star_out);
            }
        }
    }
}
